import { defineStore } from 'pinia'
import { listTags, createTag, deleteTag } from '@/api/tags'

export interface Tag {
  id: number
  name: string
  color?: string
  [k: string]: any
}

interface State {
  list: Tag[]
  loading: boolean
  loaded: boolean
  error: string | null
}

export const useTagsStore = defineStore('tags', {
  state: (): State => ({
    list: [],
    loading: false,
    loaded: false,
    error: null,
  }),
  persist: {
    key: 'mirrorforest-tags-store',
    storage: window.localStorage,
    paths: ['list', 'loaded'],
  } as any,
  getters: {
    options: (state) => state.list.map(t => ({ label: t.name, value: t.id })),
    byId: (state) => (id: number) => state.list.find(t => t.id === id),
  },
  actions: {
    async fetch(force = false) {
    //   if (this.loaded && !force) return
    //   console.log('Fetching tags')
      this.loading = true
      this.error = null
      try {
        // console.log('Fetching tags')
        const res: any = await listTags()
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '加载标签失败')
        const list = (res?.data?.list ?? res?.data ?? []) as Tag[]
        this.list = Array.isArray(list) ? list : []
        this.loaded = true
      } catch (e: any) {
        this.error = e?.message || '加载标签失败'
        throw e
      } finally {
        this.loading = false
      }
    },
    async add(name: string) {
      const payload = { name: (name || '').trim() }
      if (!payload.name) throw new Error('标签名不能为空')
      const res: any = await createTag(payload)
      const ok = res && (res.success === true || res.code === 0 || res.code === 200)
      if (!ok) throw new Error(res?.message || '创建标签失败')
      const created = (res?.data ?? null) as Tag | null
      if (created && typeof created.id === 'number') {
        // 避免重复
        const existingIndex = this.list.findIndex(t => t.id === created.id)
        if (existingIndex === -1) {
          // 使用 Vue.set 或者直接替换整个数组以确保响应式更新
          this.list = [...this.list, created]
        } else {
          // 如果已存在，更新它
          this.list.splice(existingIndex, 1, created)
        }
        return created
      }
      // 后端未返回实体，回退为仅本地显示（无 id 不加入）
      return null
    },
    async remove(id: number) {
      if (typeof id !== 'number') throw new Error('无效的标签ID')
      const res: any = await deleteTag(id)
      const ok = res && (res.success === true || res.code === 0 || res.code === 200)
      if (!ok) throw new Error(res?.message || '删除标签失败')
      this.list = this.list.filter(t => t.id !== id)
    }
  }
})
